package com.yjf.ljr.activity;

import java.io.File;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yjf.ljr.R;
import com.yjf.ljr.application.MyApplication;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.parser.DataClass;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.service.AutoLoginService;
import com.yjf.ljr.util.SPreferences;
import com.yjf.ljr.util.UploadImage;

public class IjActivity extends FragmentActivity implements OnGestureListener {

	protected ProgressDialog mProgressDialog;
	// protected ProgersssDialogCustom mProgressDialog;
	public Handler mHandler = new Handler();
	protected IjActivity mContext;
	private boolean mIsDestroy = true;
	private GestureDetector mGestureDetector;
	public static final int FLEEP_DISTANCE = 120;

	private boolean isVerify = true;
	private final String ISFOREGROUND_KEY = "ISFOREGROUND_KEY";
	private boolean isForeGround = true;
	private MyApplication mApplication;

	public void setContentView(int layoutResID) {
		View v = LayoutInflater.from(this).inflate(layoutResID, null);
		initComponents(this, v, this);
		super.setContentView(v);
	};

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
						| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		mContext = this;
		mIsDestroy = false;
		mGestureDetector = new GestureDetector(this);
		new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (mGestureDetector.onTouchEvent(event)) {
					return true;
				}
				return false;
			}
		};

		mApplication = (MyApplication) getApplication();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("userid", CommonData.USERID);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		CommonData.USERID = savedInstanceState.getString("userid");
	}

	@Override
	protected void onDestroy() {
		dismissProgressDialog();
		mIsDestroy = true;
		mHandler = null;
		super.onDestroy();
	}

	public void showProgressDialog() {
		showProgressDialog(null);
	}

	public void showProgressDialog(String strShow) {

		if (mIsDestroy) {
			return;
		}
		if (mProgressDialog == null) {
			LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = inflater.inflate(R.layout.progress_dialog, null);
			ImageView img = (ImageView) view.findViewById(R.id.progress_dialog_img);
			TextView txt = (TextView) view.findViewById(R.id.progress_dialog_txt);
			Animation anim = AnimationUtils.loadAnimation(mContext, R.anim.loading_dialog_progressbar);
			img.setAnimation(anim);
			mProgressDialog = ProgressDialog.show(this, "",
					TextUtils.isEmpty(strShow) ? getResources().getString(R.string.loading) : strShow);
			if (TextUtils.isEmpty(strShow)) {
				txt.setText("加载中");
			} else {
				txt.setText(strShow);
			}
			mProgressDialog.setContentView(view);
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.setCancelable(true);
		} else {
            if(!mProgressDialog.isShowing())
			mProgressDialog.show();
		}
	}

	public void dismissProgressDialog() {

		if (mIsDestroy) {
			return;
		}

		if (mHandler != null) {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					if (null != mProgressDialog && mProgressDialog.isShowing()) {
						try {
							mProgressDialog.dismiss();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
	}

	/**
	 * 设置左边按钮事件
	 */
	public void setLeftBtnClick() {
		Button btnLeft = (Button) findViewById(R.id.btn_title_left);
		if (btnLeft != null) {
			btnLeft.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					finish();
				}
			});
		}
	}

	/**
	 * 设置标题
	 */
	public void setTitleStr(String title) {
		if (null == title) {
			return;
		}
		TextView tv = (TextView) findViewById(R.id.tv_title);
		if (tv != null) {
			tv.setText(title);
			tv.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 设置右边按钮内容
	 */
	public void setRightStr(String str) {
		if (null == str) {
			return;
		}
		TextView tv = (TextView) findViewById(R.id.tv_title_right);
		if (tv != null) {
			tv.setText(str);
			tv.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 赋予右边按钮新的View
	 */
	public void setRightView(View view) {
		if (null == view) {
			return;
		}
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.btn_title_right);
		if (layout != null) {
			layout.removeAllViews();
			layout.addView(view);
		}
	}

	protected void showToast(String message) {
		Toast.makeText(IjActivity.this, message, Toast.LENGTH_SHORT).show();
	}

	protected String requestDataAndGetErrorMsg(RequestObject reqObj, DataClass dc) {
		String requestUrl = RequestBuilder.build(reqObj);
		String failStr = "";
		try {
			IjConnect.doRequest(requestUrl, dc);
			if (dc.code == null) {
				failStr = getResources().getString(R.string.loaddata_exception);
			} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
				failStr = dc.msg;
			}
		} catch (Exception e) {
			failStr = getResources().getString(R.string.loaddata_exception);
			e.printStackTrace();
		}
		return failStr;
	}

	protected String uploadFileAndGetErrorMsg(RequestObject reqObj, String filePath, DataClass dc) {
		return uploadFileAndGetErrorMsg(reqObj, filePath, dc, CommonData.SEVER_HOST);
	}

	/**
	 * POST方式上传文件，返回解析后的json数据
	 * 
	 * @param reqObj
	 *            请求的参数
	 * @param url
	 *            基础Url
	 * @param filePath
	 *            被上传的文件路径
	 * @param dc
	 *            解析json的数据结构
	 * @return 错误信息，空表示获取成功
	 */
	protected String uploadFileAndGetErrorMsg(RequestObject reqObj, String filePath, DataClass dc, String url) {
		String requestUrl = RequestBuilder.build(reqObj, url);
		String failStr = "";
		String strResult = "";
		try {
			strResult = UploadImage.uploadFile(new File(filePath), requestUrl);
			dc.getDataClassFromStr(strResult);
			if (dc.code == null) {
				failStr = getResources().getString(R.string.loaddata_exception);
			} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
				failStr = dc.msg;
			}
		} catch (Exception e) {
			failStr = getResources().getString(R.string.loaddata_exception);
			e.printStackTrace();
		}
		return failStr;
	}

	/**
	 * 通过反射初始化控件，要求控件的名字和布局文件名字一致,不一致通过ID注解进行配置
	 * */
	@SuppressWarnings("rawtypes")
	public static void initComponents(Context ctx, View v, Object holder) {
		Class clazz = holder.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			Class type = field.getType();
			if (View.class.isAssignableFrom(type)) {
				String idName = field.getName();

				// 如果字段上有注解则采用注解的id
				ID idAnnotation = field.getAnnotation(ID.class);
				if (idAnnotation != null) {
					idName = idAnnotation.value();
				}

				View view = v.findViewById(ctx.getResources().getIdentifier(idName, "id", ctx.getPackageName()));
				try {
					if (view != null) {
						field.set(holder, view);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 这里必须添加@Retention(RetentionPolicy.RUNTIME)，不然程序运行过程中获取不到注解
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	// 只能将注解加到方法上
	/**控件上的ID注解*/
	public @interface ID {
		String value();
	}

	/** 跳转到Webview登录 **/
	public void loginWebview() {
		CommonData.FLAG_LOGIN_SERVER = false;
		MyAccountActivity.gIsLoginServer = false;
		CommonData.IS_LOGIN = false;
		
		dismissProgressDialog();
		
//		String userName = SPreferences.getUserName(this);
//    	String pwd = SPreferences.getPassword(this);
//    	boolean isLockPatternOpen = (Boolean) SPreferences.getData(this, false, CommonData.USER_NAME
//				+ LockPatternSettingActivity.LOCK_PATTERN_IS_OPEN);
//		if(CommonData.IS_LOGIN && isLockPatternOpen && !TextUtils.isEmpty(userName) && !TextUtils.isEmpty(pwd)) {
//			if(!LockPatternActivity.IS_SHOW){
//				Intent intent = new Intent();
//				intent.setClass(getApplicationContext(), LockPatternActivity.class);				
//				startActivityForResult(intent, CommonData.REQUEST_CODE_LOGIN);
//			}
//		} else {
			Intent intent = new Intent();
			// intent.setClass(this, WvLoginActivity.class);
			intent.setClass(this, LoginActivity.class);
			// intent.putExtra("advUrl", CommonData.LOGIN_URL);
			// intent.putExtra("advTitle", "登录");
			// intent.putExtra("registration", "注册");

			startActivityForResult(intent, CommonData.REQUEST_CODE_LOGIN);
//		}
		
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		if (mGestureDetector.onTouchEvent(event)) {
			event.setAction(MotionEvent.ACTION_CANCEL);
		}
		return super.dispatchTouchEvent(event);
	}

	// OnGestureListener接口
	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		float xOff = e1.getX() - e2.getX();
		float yOff = e1.getY() - e2.getY();
		if (xOff <= (-FLEEP_DISTANCE) && Math.abs(xOff) - FLEEP_DISTANCE / 2 > Math.abs(yOff)) { // 左划并且绝对值要大
			finish();
		} else if (xOff >= FLEEP_DISTANCE && Math.abs(xOff) - FLEEP_DISTANCE / 2 > Math.abs(yOff)) { // 右划
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	@Override
	protected void onResume() {
		super.onResume();
		isForeGround = (Boolean) SPreferences.getData(this, false, ISFOREGROUND_KEY);
		if (!isForeGround) {
			if (!TextUtils.isEmpty(CommonData.USER_NAME)) {
				boolean isLockPatternOpen = (Boolean) SPreferences.getData(this, false, CommonData.USER_NAME
						+ LockPatternSettingActivity.LOCK_PATTERN_IS_OPEN);
				if (isLockPatternOpen) {
					if (isVerify() && CommonData.IS_LOGIN) {
						mApplication.verify(this);
					}
				}
			}
			SPreferences.saveData(this, true, ISFOREGROUND_KEY);
		}
	}

//	@Override
//	protected void onStart() {
//		super.onStart();
//		isForeGround = (Boolean) SPreferences.getData(this, false, ISFOREGROUND_KEY);
//		if (!isForeGround) {
//			if (!TextUtils.isEmpty(CommonData.USER_NAME)) {
//				boolean isLockPatternOpen = (Boolean) SPreferences.getData(this, false, CommonData.USER_NAME
//						+ LockPatternSettingActivity.LOCK_PATTERN_IS_OPEN);
//				if (isLockPatternOpen) {
//					if (isVerify() && CommonData.IS_LOGIN) {
//						mApplication.verify();
//					}
//				}
//			}
//			SPreferences.saveData(this, true, ISFOREGROUND_KEY);
//		}
//	}

	@Override
	protected void onPause() {
		super.onPause();
		boolean isScreenOn = mApplication.isScreenOn(this);
		if (!isScreenOn) {
			SPreferences.saveData(this, isScreenOn, ISFOREGROUND_KEY);
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		isForeGround = mApplication.isRunningForeground(this);
		if (!isForeGround) {
			SPreferences.saveData(this, isForeGround, ISFOREGROUND_KEY);
		}
	}

	public boolean isVerify() {
		return isVerify;
	}

	public void setVerify(boolean isVerify) {
		this.isVerify = isVerify;
	}
}